﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace SimpleTaskSystem
{
    public class TaskManager : MonoBehaviour
    {
        public delegate void TaskManagerHandler();
        public event TaskManagerHandler onStart;
        public event TaskManagerHandler onOver;
        /// <summary>
        /// 所有任务
        /// </summary>
        public List<Task> tasks = new List<Task>();
        [HideInInspector]
        public bool isOver { get; private set; }
        int currentIndex = -1; 

        private void Awake()
        {
            isOver = false;
            for (int i = 0; i < tasks.Count; i++)
            {
                for (int j = 0; j < tasks[i].operations.Count; j++)
                {
                    OperationMessage.AddOperation(tasks[i].operations[j]);
                }
            }
            foreach (var item in tasks)
            {
                item.InitTask();
            }
        }
        /// <summary>
        /// 开始任务
        /// </summary>
        public void StartTask()
        {
            SetNextTask();
            if (onStart != null)
            {
                onStart();
            }
        }
        /// <summary>
        /// 一个任务完成
        /// </summary>
        /// <param name="task"></param>
        public void OneTaskCompleted(Task task)
        {
            task.onCompleted -= OneTaskCompleted;
            SetNextTask();
        }

        public Task GetCurrentTask()
        {
            if (currentIndex < 0 || currentIndex >= tasks.Count)
            {
                return null;
            }
            return tasks[currentIndex];
        }

        void SetNextTask()
        {
            currentIndex++;
            if (currentIndex >= tasks.Count)
            {
                Over();
                return;
            }
            tasks[currentIndex].onCompleted += OneTaskCompleted;
            tasks[currentIndex].Excute();
        }

        void Over()
        {
            if (onOver != null)
            {
                onOver();
            }
            isOver = true;
            Debug.Log("Over");
        }
    }
}
